/* 封装axios用于发送请求 */
import router from '@/router'
import axios from 'axios'
import { Toast } from 'vant'
import { delToken, getToken } from '@/utils/storage'

// 创建一个新的axios实例
const request = axios.create({
  baseURL: 'http://liufusong.top:8080/',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(function (config) {
  const token = getToken()
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, function (err) {
  return Promise.reject(err)
})

// 响应拦截器
request.interceptors.response.use(function (response) {
  return response.data
},
  function (error) {
  console.log(error.response);
  if (error.response) {
    if (error.response.status === 400|| error.response.status === 401) {
      delToken()
      router.push('/login')
    } else { Toast(error.response.data.message) }
  }
  return Promise.reject(error)
})
export default request